const Router = require('koa-router');
const refereeCtl= require('../../controllers/referees.js')
const router = new Router();
let s = '';
let res = {};
var net = require('net');
//创建TCP客户端
var client = new net.Socket();
client.setEncoding('utf8');
client.connect(7002,'192.168.31.778',function () {
    //console.log('已连接到服务器');
    client.write('你好');
    //指定10秒后关闭与服务器的连接
    setTimeout(function () {
        //客户端的socket端口对象可以调用end方法来结束与服务端的连接，同时服务端添加end事件的监听事件即可。
        client.end('再见','utf8');
    },10000);
});
//console.log(1)
//let s = ''
client.on('data',function (data) {
    
    console.log('已接受服务器端发送的数据：'+data);
    //console.log(data.slice(1));
    //let ret = []
    for (let a of data){
        //console.log(a)
        s = s + a;
        if (a == '\n'){
            let result  = s;
            //console.log(result);
            var json = eval('('+result+')');
            let  b = json.data;
            /**cardId = b.cardid;
            x = b.x;
            y = b.y;
            z = b.z;*/
            let c = {
                'cardId': b.cardid,
                'x': parseFloat((b.x/16*100).toFixed(3)),
                'y': parseFloat((b.y/7*100).toFixed(3)),
                //'z': parseFloat((b.z).toFixed(3))
            }
            res[b.cardid] = c;
            s = '';
        }
    }
    //res = ret
    /**s = s + 1;
    console.log(s+'\n')
    console.log(1)*/
});
//监听与服务端连接的错误事件
client.on('error',function (err) {
    console.log('在于服务器连接或通信过程中发生了一个错误，错误代码为%s',err.code);
    //当发生错误时，用destroy方法销毁该socket端口。确保不会再被利用
    client.destroy();
})
/**
 * @swagger
 * tags:
 *   - name: competition
 *     description: Everything about competition
 */

router
/**
 * @swagger
 * paths:
 *   /competitions:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return a list of competitions
 *       description: ''
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             type: array
 *             items:
 *               $ref: '#/definitions/Competition'
 */
    .get('/', async (ctx, next)=>{ ctx.body = await refereeCtl.list(); })

/**
 * @swagger
 * paths:
 *   /competitions:
 *     post:
 *       tags:
 *         - competition
 *       summary: Create a competition
 *       description: ''
 *       parameters:
 *         - in: body
 *           name: "body"
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/Competition"
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .post('/', async (ctx, next)=>{
        const {id} = ctx.params;
        const data = ctx.request.body;
        for(let key of Object.keys(data)){
            let a = data[key]
            const  r = await refereeCtl.create(a);
            //console.log(a)
        }
    })

    .post('/demo1', async (ctx, next)=>{
        //const {id} = ctx.params;
        const exec = require('child_process').exec;
        const data = ctx.request.body;
        exec('python /home/soccer/Desktop/NewSoccerEnd/soccer-analysis/soccerAPI/app/routes/api_v1/demo1.py',function(error,stdout,stderr){
            if(error) {
                console.info('stderr : '+stderr);
            }
            console.log('exec: ' + stdout);
        })
    })

    .get('/uwb', async (ctx, next)=>{
        ctx.body = Object.keys(res).map(key => res[key]);        
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return a competition
 *       description: ''
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             $ref: '#/definitions/Competition'
 */
    .get('/:id', async (ctx, next)=>{
        // Retrieves informations about a given competition
        const {id} = ctx.params;
        const r = await refereeCtl.retrieve(id);
        ctx.assert(r !== null, 404, 'Detail not found!');

        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     put:
 *       tags:
 *         - competition
 *       summary: Update or create a competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *         - in: body
 *           name: body
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/Competition"
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .put('/:id', async (ctx, next)=>{
        const id = ctx.params.id;
        const data = ctx.request.body;
        const r = await refereeCtl.upsert(id, data);
        
        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     delete:
 *       tags:
 *         - competition
 *       summary: Delete a competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         204:
 *           description: No content
 */
    .delete('/:id', async (ctx, next)=>{
        refereeCtl.removeById(ctx.params.id);
        ctx.status = 204;
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}/seasons:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return the list of seasons of the given competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:id/seasons', async (ctx, next)=>{
        const {id} = ctx.params;
        ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);
    })

module.exports = router;

/**
 * @swagger
 * resourcePath: /api
 * description: All about API
 * definitions:
 *   Competition:
 *     type: "object"
 *     required:
 *       - "name"
 *     properties:
 *       id:
 *         type: "string"
 *       name:
 *         type: "string"
 *       area:
 *         type: "string"
 *       foramt:
 *         type: "string"
 *         enum:
 *           - "Domestic cup"
 *           - "Domestic league"
 *           - "Domestic super cup"
 *           - "International cup"
 *           - "International super cup"
 *       type:
 *         type: "string"
 *         enum:
 *          - club
 *          - inernational
 *       categroy: 
 *         type: "string"
 *         enum:
 *          - defalut
 *          - U12
 *          - U13
 *          - U14
 *          - U15
 *          - U16
 *          - U17
 *          - U18
 *          - U19
 *          - U20
 *          - U21
 *          - U22
 *          - U23
 *       gender: 
 *         type: "string"
 *         enum:
 *           - male
 *           - female
 *       divisionLevel:
 *         type: "number"
 *         enum:
 *           - 0
 *           - 1
 *           - 2
 *           - 3
 *           - 4
 *           - 5
 */